<?php

$auth = Auth::getAuth('current_user');
$db = new Database;
$fs = new functions;
$upload = new upload();
$search = new Search();



if(Auth::hasAuth('current_user')){
    if(isset($_POST["user_id"]) ){
        $old_log_authid = $_POST["user_id"];
        if( $auth["id"] != $old_log_authid ){
            echo "not same id";
            return;
        }
    }
    if (isset($_POST['action'])) {
        $date = $fs->currentDateTime();

        switch ($_POST['action']) {

            // Save workspace to the databasea

            case "saveWorkspace":
                //$workspace = $_POST['workspace'];
                $json_return = array();
                $data = $_POST['json_encode'];
                $json = json_decode($data, true);
                $fields = $json['form_fields'];
                $formId = $_POST['formId'];
               

                $workspace_content = str_replace('\\', '', $json['WorkspaceContent']);
                $reservedFields = array('TrackNo'
                    , 'Requestor', 'Status', 'Processor', 'LastAction', 'DateCreated'
                    , 'DateUpdated', 'CreatedBy', 'UpdatedBy', 'Unread', 'Node_ID', 'Workflow_ID', 'fieldEnabled', 'fieldRequired', 'fieldHiddenValues', 'imported', 'Repeater_Data', 'Editor','Viewer',"middleware_process");

                // Insert record to the database of tb_workspace    
                //
                $fields_decode = json_decode($fields, true);

                if ($formId == '0') {
                     $tblname = $json['Title'];

                     $tblname = $auth['company_id'] . '_tbl_' . str_replace(' ', '', $tblname);

                     //admin
                     $jsonAdmin = json_decode($json["form-admin"],true);
                    array_push($jsonAdmin['users'], $auth['id']);
                    $jsonAdmin = json_encode($jsonAdmin);

                    //insert array for new form
                    $insert = array("form_name" => $json['Title'],
                        "form_table_name" => $tblname,
                        "form_description" => $json['DisplayName'],
                        "form_content" => $workspace_content,
                        "form_buttons" => $json['BtnName'],
                        "created_by" => $auth['id'],
                        "updated_by" => $auth['id'],
                        "company_id" => $auth['company_id'],
                        "reference_prefix" => $json['Prefix'],
                        "reference_type" => $json['Type'],
                        "version" => 1,
                        "form_json" => $data,
                        "date_created" => $date,
                        "button_content" => $json['button_content'],
                        "active_fields" => $json["existing_fields"],
                        "date_updated" => $date,
                        "is_active" => 1,
                        "MobileJsonData" => $json["MobileJsonData"],
                        "MobileContent" => $json["MobileContent"],
                        "form_authors" => $json["form_authors"],
                        "form_viewers" => $json["form_viewers"],
                        "form_admin" => $jsonAdmin
                    );

                    $array_condition = array("form_table_name" => $tblname);
                    $formCount = $search->getSpecificForms($array_condition);
                    if (count($formCount) > 0) {
                        $message = "This form is already created";
                        $json_return = array("status" => "warning",
                            "message" => $message);
                        echo json_encode($json_return);
                    } else {
                        $strSQL = 'CREATE TABLE ' . $tblname . ' (';
                        $strSQL.= ' ID int PRIMARY KEY AUTO_INCREMENT, ';

                        foreach ($reservedFields as $field_name) {
                            if ($field_name == 'DateCreated' || $field_name == 'DateUpdated') {
                                $strSQL .= $field_name . ' datetime,';
                            } else {
                                $strSQL .= $field_name . ' longtext,';
                            }
                        }

                        $strSQL = substr($strSQL, 0, $strSQL - 1);
                        $strSQL .= ' ) ';


                        $tblID = $db->create($strSQL);

                        $workspaceID = $db->insert("tb_workspace", $insert);
                        // Create folder for the postImage

                        $path = "images/formLogo";
                        $id_encrypt = md5(md5($workspaceID));
                        $dir = $path . "/" . $id_encrypt;
                        if (!is_dir($filename)) {
                            $upload->createFolder($dir);
                        }

                        // Move files to the directory
                        $copy_foldername = md5(md5($auth['id']));
                        $from = "images/formLogo/temporaray_files/" . $copy_foldername;
                        $postFiles = $upload->getAllfiles_fromDirectory($from);

                        foreach ($postFiles as $file) {
                            copy($from . '/' . $file, $dir . '/' . $file);
                        }
                        $upload->unlinkRecursive($from, "yes");
                        rmdir($from);

                        $message = "Your form (" . $json['Title'] . ") was successfully created.";
                        $json_return = array("status" => "success",
                            "message" => $message,
                            "saved_form_id" => $workspaceID);
                        echo json_encode($json_return);
                    }
                } else {
                    $jsonAdmin = json_decode($json["form-admin"],true);
                    array_push($jsonAdmin['users'], $auth['id']);
                    $jsonAdmin = json_encode($jsonAdmin);


                    $formDoc = new Form($db, $formId);
                    $tblname = $formDoc->form_table_name;
                    $insert = array("form_name" => $json['Title'],
                        "form_description" => $json['DisplayName'],
                        "form_content" => $workspace_content,
                        "form_buttons" => $json['BtnName'],
                        "created_by" => $auth['id'],
                        "updated_by" => $auth['id'],
                        "company_id" => $auth['company_id'],
                        "reference_prefix" => $json['Prefix'],
                        "reference_type" => $json['Type'],
                        "version" => 1,
                        "form_json" => $data,
                        // "date_created" => $date,
                        "button_content" => $json['button_content'],
                        "active_fields" => $json["existing_fields"],
                        "date_updated" => $date,
                        "is_active" => 1,
                        "MobileJsonData" => $json["MobileJsonData"],
                        "MobileContent" => $json["MobileContent"],
                        "form_authors" => $json["form_authors"],
                        "form_viewers" => $json["form_viewers"],
                        "form_admin" => $jsonAdmin
                    );

                    $condition = array("ID" => $formId);
                    $workspaceID = $db->update("tb_workspace", $insert, $condition);

                    // Create folder for the postImage
                    $path = "images/formLogo";
                    $id_encrypt = md5(md5($formId));
                    $dir = $path . "/" . $id_encrypt;
                    if (!is_dir($filename)) {
                        $upload->createFolder($dir);
                    }

                    // Move files to the directory
                    $copy_foldername = md5(md5($auth['id']));
                    $from = "images/formLogo/temporaray_files/" . $copy_foldername;
                    $postFiles = $upload->getAllfiles_fromDirectory($from);

                    foreach ($postFiles as $file) {
                        copy($from . '/' . $file, $dir . '/' . $file);
                    }
                    $upload->unlinkRecursive($from, "yes");
                    rmdir($from);
                    $message = "Your form (" . $json['Title'] . ") was successfully updated.";
                    $json_return = array("status" => "success",
                        "message" => $message,
                        "update" => $insert);
                    echo json_encode($json_return);
                }


                foreach ($reservedFields as $key => $value) {
                    $fieldName = $value;
                    //$strSQL.=$fieldName.' '.$fieldType.',';   
                    if ($fieldName == 'DateCreated' || $fieldName == 'DateUpdated') {
                        $fieldType = " datetime ";
                    } else {
                        $fieldType = " longtext ";
                    }

                    $alterSQL = 'ALTER TABLE ' . $tblname . ' ADD ' . $fieldName . ' ' . $fieldType . ' ';
                    $db->create($alterSQL);
                }

                foreach ($fields_decode as $field) {
                    $fieldName = functions::removePairedBracket($field['fieldName']);
                    $fieldType = $field['fieldType'];
                    //$strSQL.=$fieldName.' '.$fieldType.',';
                    //$dropSQL = 'ALTER TABLE ' . $tblname . ' DROP ' . $fieldName;
                    //$db->create($dropSQL);
                    
                    $active_fields = split(",",$formDoc->active_fields);
                    $field_index = in_array($fieldName, $active_fields);
                    
                    if($field_index){
                        //update field
                        $alterSQL = 'ALTER TABLE ' . $tblname . ' MODIFY ' . $fieldName . ' ' . $fieldType . ' ';
                    }else{
                        //new field
                        $alterSQL = 'ALTER TABLE ' . $tblname . ' ADD ' . $fieldName . ' ' . $fieldType . ' ';
                    }
                    
                    $db->create($alterSQL);
                }



                //echo $formId;
                //echo "Your form (" . $json['Title'] . ") was successfully saved.";

                break;

            // Get Form  created workspace on the database

            case "getForm":

                $getForm = $db->query("SELECT * FROM tb_workspace WHERE company_id = {$db->escape($auth['company_id'])}", "array");

                foreach ($getForm as $value) {
                    $form[] = array(
                        "form_name" => $value['form_name'],
                        "form_id" => $value['id']
                    );
                }
                echo json_encode($form);
                break;

            // Get Form Category

            case "getCategory":
                $getCategory = $db->query("SELECT * FROM tbform_category WHERE company_id = {$db->escape($auth['company_id'])}", "array");

                foreach ($getCategory as $category) {
                    $categ[] = array(
                        "category_name" => $category['category_name'],
                        "category_id" => $category['id']
                    );
                }
                echo json_encode($categ);
                break;
            case "getFormList":
                $search = new Search();
                $getForms = $search->getForms();
                echo json_encode($getForms);
                break;
        }
    }
}else{
    echo "false";
}
    
?>